import Message from 'tdesign-miniprogram/message/index';
import { novelAPI } from '~/api/novel';
import { interactionAPI } from '~/api/interaction';
const authUtils = require('~/utils/auth.js');
const apiHelper = require('~/utils/api-helper.js');

Page({
  data: {
    // 小说数据
    novelData: null,
    novelId: '',
    
    // 章节列表
    chapters: [],
    
    // 评论相关
    comments: [],
    commentContent: '',
    replyTarget: '', // 回复目标用户昵称
    replyCommentId: '', // 回复的评论ID
    
    // 权限状态
    canWrite: false,
    
    // 加载状态
    loading: false,
    
    // 分页信息
    commentsPagination: {
      page: 1,
      pageSize: 20,
      hasMore: true
    }
  },

  /**
   * 页面加载
   */
  onLoad(options) {
    const { novelId } = options;
    if (!novelId) {
      Message.error({
        context: this,
        content: '小说ID不能为空'
      });
      wx.navigateBack();
      return;
    }

    this.setData({ novelId });
    this.loadNovelData();
  },

  /**
   * 页面显示
   */
  onShow() {
    // 刷新数据
    if (this.data.novelId) {
      this.loadNovelData();
    }
  },

  /**
   * 下拉刷新
   */
  onPullDownRefresh() {
    this.loadNovelData();
  },

  /**
   * 加载小说数据
   */
  async loadNovelData() {
    try {
      this.setData({ loading: true });
      
      // 使用API辅助工具并行加载数据
      const [novelResult, chaptersResult, commentsResult] = await Promise.all([
        apiHelper.safeApiCall(
          () => novelAPI.getNovelDetail(this.data.novelId),
          { dataProcessor: apiHelper.processNovelData }
        ),
        apiHelper.safeApiCall(
          () => novelAPI.getNovelChapters(this.data.novelId)
        ),
        apiHelper.safeApiCall(
          () => interactionAPI.getComments(interactionAPI.TARGET_TYPES.NOVEL, this.data.novelId, {
            page: 1,
            pageSize: this.data.commentsPagination.pageSize
          }),
          { dataProcessor: (data) => apiHelper.processPaginationData({ data }, []) }
        )
      ]);

      // 处理小说详情
      if (novelResult.success) {
        this.setData({ novelData: novelResult.data });
        
        // 检查写作权限
        if (authUtils.isLoggedIn() && novelResult.data.isParticipant) {
          this.checkWritePermission();
        }
      }

      // 处理章节列表
      if (chaptersResult.success) {
        this.setData({ chapters: chaptersResult.data || [] });
      }

      // 处理评论列表
      if (commentsResult.success) {
        const processedComments = apiHelper.processCommentList(commentsResult.data.list || []);
        this.setData({ 
          comments: processedComments,
          'commentsPagination.hasMore': commentsResult.data.hasMore || false
        });
      }

      // 如果有任何加载失败，显示错误信息
      if (!novelResult.success || !chaptersResult.success || !commentsResult.success) {
        Message.warning({
          context: this,
          content: '部分数据加载失败，请下拉刷新重试'
        });
      }

    } catch (error) {
      console.error('加载小说数据失败:', error);
      Message.error({
        context: this,
        content: '加载数据失败，请重试'
      });
    } finally {
      this.setData({ loading: false });
      wx.stopPullDownRefresh();
    }
  },

  /**
   * 检查写作权限
   */
  async checkWritePermission() {
    try {
      const response = await novelAPI.canWriteNextChapter(this.data.novelId);
      if (response.code === 200) {
        // 多人创作时，即使有完结投票进行中，也允许写作
        // 因为投票期间应该允许继续创作
        this.setData({ canWrite: response.data });
      }
    } catch (error) {
      console.error('检查写作权限失败:', error);
    }
  },

  /**
   * 点赞小说
   */
  async onLike() {
    if (!authUtils.isLoggedIn()) {
      authUtils.redirectToLogin();
      return;
    }

    const { novelData } = this.data;
    const interactionHelper = apiHelper.createInteractionHelper(this, 'novelData');
    
    const apiCall = novelData.isLiked ? 
      () => interactionAPI.novel.unlike(this.data.novelId) :
      () => interactionAPI.novel.like(this.data.novelId);

    await interactionHelper.toggleLike(
      apiCall,
      novelData.isLiked,
      novelData.likeCount || 0
    );
  },

  /**
   * 收藏小说
   */
  async onFavorite() {
    if (!authUtils.isLoggedIn()) {
      authUtils.redirectToLogin();
      return;
    }

    const { novelData } = this.data;
    const interactionHelper = apiHelper.createInteractionHelper(this, 'novelData');
    
    const apiCall = novelData.isFavorited ? 
      () => interactionAPI.novel.unfavorite(this.data.novelId) :
      () => interactionAPI.novel.favorite(this.data.novelId);

    await interactionHelper.toggleFavorite(
      apiCall,
      novelData.isFavorited,
      novelData.favoriteCount || 0
    );
  },

  /**
   * 分享
   */
  onShare() {
    // TODO: 实现分享功能
    Message.info({
      context: this,
      content: '分享功能开发中'
    });
  },

  /**
   * 加入小说
   */
  async onJoinNovel() {
    if (!authUtils.isLoggedIn()) {
      authUtils.redirectToLogin();
      return;
    }

    try {
      const response = await novelAPI.joinNovel(this.data.novelId);
      if (response.code === 200) {
        Message.success({
          context: this,
          content: '加入成功！'
        });
        
        // 刷新小说数据
        this.loadNovelData();
      }
    } catch (error) {
      console.error('加入小说失败:', error);
      Message.error({
        context: this,
        content: error.message || '加入失败，请重试'
      });
    }
  },

  /**
   * 写下一章
   */
  onWriteChapter() {
    if (!authUtils.isLoggedIn()) {
      authUtils.redirectToLogin();
      return;
    }

    wx.navigateTo({
      url: `/pages/chapter-write/index?novelId=${this.data.novelId}`
    });
  },

  /**
   * 完结小说
   */
  async onCompleteNovel() {
    if (!authUtils.isLoggedIn()) {
      authUtils.redirectToLogin();
      return;
    }

    const { novelData } = this.data;
    
    // 检查是否为多人创作
    if (novelData.creationType === 2) {
      // 检查是否已有投票进行中
      if (novelData.completeVote && novelData.completeVote.status === 'voting') {
        Message.info({
          context: this,
          content: '已有完结投票进行中，请等待投票结果'
        });
        return;
      }
      
      // 多人创作需要发起完结投票
      wx.showModal({
        title: '发起完结投票',
        content: `确定要发起完结这部小说的投票吗？\n\n需要${novelData.participants.length}位参与者中超过半数同意才能完结。\n\n注意：投票期间仍可继续写作。`,
        confirmText: '发起投票',
        cancelText: '取消',
        success: async (res) => {
          if (res.confirm) {
            try {
              // 发起完结投票
              const response = await novelAPI.initiateCompleteVote(this.data.novelId);
              if (response.code === 200) {
                Message.success({
                  context: this,
                  content: '完结投票已发起，等待其他参与者投票'
                });
                
                // 刷新数据
                this.loadNovelData();
              }
            } catch (error) {
              console.error('发起完结投票失败:', error);
              Message.error({
                context: this,
                content: error.message || '发起投票失败，请重试'
              });
            }
          }
        }
      });
    } else {
      // 单人创作可以直接完结
      wx.showModal({
        title: '确认完结',
        content: '确定要完结这部小说吗？完结后将无法继续写作。',
        success: async (res) => {
          if (res.confirm) {
            try {
              const response = await novelAPI.completeNovel(this.data.novelId);
              if (response.code === 200) {
                Message.success({
                  context: this,
                  content: '小说已完结'
                });
                
                // 刷新数据
                this.loadNovelData();
              }
            } catch (error) {
              console.error('完结小说失败:', error);
              Message.error({
                context: this,
                content: error.message || '完结失败，请重试'
              });
            }
          }
        }
      });
    }
  },

  /**
   * 处理完结投票
   */
  async onVoteComplete(e) {
    const voteType = e.currentTarget.dataset.voteType;
    if (!authUtils.isLoggedIn()) {
      authUtils.redirectToLogin();
      return;
    }

    const { novelData } = this.data;
    const actionText = voteType === 'agree' ? '同意完结' : '反对完结';
    
    wx.showModal({
      title: `确认${actionText}`,
      content: `确定要${actionText}这部小说吗？`,
      success: async (res) => {
        if (res.confirm) {
          try {
            const apiMethod = voteType === 'agree' ? novelAPI.voteForComplete : novelAPI.voteAgainstComplete;
            const response = await apiMethod(this.data.novelId);
            
            if (response.code === 200) {
              Message.success({
                context: this,
                content: `您已${actionText}`
              });
              
              // 刷新数据
              this.loadNovelData();
            }
          } catch (error) {
            console.error(`${actionText}失败:`, error);
            Message.error({
              context: this,
              content: error.message || `${actionText}失败，请重试`
            });
          }
        }
      }
    });
  },

  /**
   * 取消完结投票
   */
  async onCancelVote() {
    if (!authUtils.isLoggedIn()) {
      authUtils.redirectToLogin();
      return;
    }

    wx.showModal({
      title: '确认取消投票',
      content: '确定要取消这次完结投票吗？',
      success: async (res) => {
        if (res.confirm) {
          try {
            const response = await novelAPI.cancelCompleteVote(this.data.novelId);
            if (response.code === 200) {
              Message.success({
                context: this,
                content: '投票已取消'
              });
              
              // 刷新数据
              this.loadNovelData();
            }
          } catch (error) {
            console.error('取消投票失败:', error);
            Message.error({
              context: this,
              content: error.message || '取消投票失败，请重试'
            });
          }
        }
      }
    });
  },

  /**
   * 阅读章节
   */
  onReadChapters() {
    if (this.data.chapters.length === 0) {
      Message.info({
        context: this,
        content: '暂无章节内容'
      });
      return;
    }

    // 跳转到第一章
    const firstChapter = this.data.chapters[0];
    wx.navigateTo({
      url: `/pages/chapter-detail/index?chapterId=${firstChapter.id}&novelId=${this.data.novelId}`
    });
  },

  /**
   * 点击章节
   */
  onChapterTap(e) {
    const chapterId = e.currentTarget.dataset.chapterId;
    console.log('点击章节:', { chapterId, novelId: this.data.novelId });
    
    if (!chapterId) {
      Message.warning({
        context: this,
        content: '章节ID无效'
      });
      return;
    }
    
    wx.navigateTo({
      url: `/pages/chapter-detail/index?chapterId=${chapterId}&novelId=${this.data.novelId}`,
      fail: (err) => {
        console.error('跳转章节详情失败:', err);
        Message.error({
          context: this,
          content: '跳转失败，请重试'
        });
      }
    });
  },

  /**
   * 回复评论
   */
  onReplyComment(e) {
    if (!authUtils.isLoggedIn()) {
      authUtils.redirectToLogin();
      return;
    }

    const commentId = e.currentTarget.dataset.commentId;
    const comment = this.data.comments.find(c => c.id === commentId);
    
    this.setData({
      replyTarget: comment ? comment.user.nickname : '',
      replyCommentId: commentId,
      commentContent: ''
    });
  },

  /**
   * 评论输入
   */
  onCommentInput(e) {
    const value = e.detail.value;
    console.log('评论输入:', value);
    this.setData({
      commentContent: value
    });
    console.log('评论内容已更新:', this.data.commentContent);
  },

  /**
   * 提交评论
   */
  async onSubmitComment() {
    console.log('点击发送按钮');
    if (!authUtils.isLoggedIn()) {
      authUtils.redirectToLogin();
      return;
    }

    const { commentContent, replyCommentId, novelId } = this.data;
    console.log('提交评论参数:', { commentContent, replyCommentId, novelId });
    
    if (!commentContent.trim()) {
      Message.warning({
        context: this,
        content: '请输入评论内容'
      });
      return;
    }

    try {
      const commentData = {
        content: commentContent.trim(),
        parentId: replyCommentId || null
      };

      console.log('评论数据:', commentData);

      if (replyCommentId) {
        // 回复评论
        console.log('回复评论:', replyCommentId);
        await interactionAPI.replyComment(replyCommentId, commentData);
      } else {
        // 直接评论
        console.log('直接评论小说:', novelId, '目标类型:', interactionAPI.TARGET_TYPES.NOVEL);
        await interactionAPI.addComment(interactionAPI.TARGET_TYPES.NOVEL, novelId, commentData);
      }

      Message.success({
        context: this,
        content: '评论成功'
      });

      // 清空输入框和回复状态
      this.setData({
        commentContent: '',
        replyTarget: '',
        replyCommentId: ''
      });

      // 刷新评论列表
      this.loadComments();
    } catch (error) {
      console.error('评论失败:', error);
      Message.error({
        context: this,
        content: error.message || '评论失败，请重试'
      });
    }
  },

  /**
   * 加载评论列表
   */
  async loadComments() {
    try {
      console.log('加载小说评论:', { novelId: this.data.novelId, targetType: interactionAPI.TARGET_TYPES.NOVEL });
      
      const response = await interactionAPI.getComments(
        interactionAPI.TARGET_TYPES.NOVEL, 
        this.data.novelId, 
        {
          page: 1,
          pageSize: this.data.commentsPagination.pageSize
        }
      );

      console.log('小说评论API响应:', response);

      if (response.code === 200) {
        const commentsData = response.data;
        console.log('小说评论数据:', commentsData);
        
        this.setData({ 
          comments: commentsData.list || [],
          'commentsPagination.hasMore': commentsData.hasMore || false
        });
      }
    } catch (error) {
      console.error('加载小说评论失败:', error);
    }
  }
});
